<template>
  <div class="app-container">
    <a-form-model ref="form" :model="model" :disabled="disabled" :rules="rules">
      <a-row>
        <a-col :span="8">
          <!-- {{ action }} -->
          <a-form-model-item label="业务员" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="operator"
            ref="operatorFmi">
            <j-select-user-by-dep :disabled="disabled" v-model="model.operator" :multi="false"
              @change="onOperatorChange" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="单据编号" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="billNo">
            <a-input :readOnly="(disabled || action == 'edit')" placeholder="请输入" v-model="model.billNo" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="单据日期" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="billDate">
            <!--JDate 清空或键盘删空，即使输入了合法日期，必填校验提示仍一直显示，故设置allowClear=false和inputReadOnly=true-->
            <j-date v-model="model.billDate" :readOnly="disabled" placeholder="请选择日期" style="width: 100%"
              :allowClear="false" :inputReadOnly="true" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="联系人" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
            <a-input placeholder="请输入" v-model="model.contact" :readOnly="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="联系电话" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
            <a-input placeholder="请输入" v-model="model.phone" :readOnly="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="电子邮件" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
            <a-input placeholder="请输入" v-model="model.email" :readOnly="disabled" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="订单总金额" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
            <a-input placeholder="请输入" v-model="model.totalAmt" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="币种" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="currency">
            <j-dict-select-tag v-model="model.currency" dictCode="bas_currency,name,code" placeholder="请选择"
              :disabled="disabled" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="订单总付款金额" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
            <a-input placeholder="请输入" v-model="model.totalPayAmount" :disabled="true" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="客户" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="customerId">
            <j-search-select-tag v-model="model.customerId" :async="true" dict="bas_customer,name,id" placeholder="请选择"
              :disabled="disabled" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="交货日期" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="deliveryDate">
            <j-date v-model="model.deliveryDate" :readOnly="disabled" placeholder="请选择交货日期" style="width: 100%"
              :allowClear="false" :inputReadOnly="true" format="YYYY-MM-DD" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item label="附件" :labelCol="labelCol1" :wrapperCol="wrapperCol3" prop="attachment">
            <j-upload v-model="model.attachment" :disabled="(disabled||action==='check')"></j-upload>
          </a-form-model-item>
        </a-col>
      </a-row>
      <!-- 操作区 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="3" v-if="action!=='check'">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd('supplier')"
            v-if="!disabled">新增供应商</el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠所有</el-button>
        </el-col>
      </el-row>

      <!-- 树形表格（箭头在供应商名称后） -->
      <el-table ref="supplierTable" v-loading="loading" :data="supplierList" row-key="jsid" border style="width: 100%;"
        @expand-change="handleExpandChange" :tree-props="{ children: 'productList' }">
        <!-- <el-table-column type="tree" prop="id" label="序号" width="50" :indent="24"></el-table-column> -->
        <!-- 供应商名称列（箭头在名称后） -->
        <el-table-column prop="supplierName" label="供应商" width="220" fixed :indent="24"></el-table-column>
        <el-table-column prop="contractNo" label="合同号" width="220" fixed :indent="24"></el-table-column>
        <!-- 产品相关列（动态显示） -->
        <el-table-column prop="productName" label="产品名称" width="180" v-if="hasExpandedSupplier">
          <template slot-scope="scope">
            <span v-if="scope.row.type === 'product'">{{ scope.row.productName }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="sealUnitAmount" label="销售单价" width="120" v-if="hasExpandedSupplier">
          <template slot-scope="scope">
            <span v-if="scope.row.type === 'product'">¥{{ scope.row.sealUnitAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="buyUnitAmount" label="采购单价" width="120" v-if="hasExpandedSupplier">
          <template slot-scope="scope">
            <span v-if="scope.row.type === 'product'">¥{{ scope.row.buyUnitAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="qty" label="数量" width="120" v-if="hasExpandedSupplier">
          <template slot-scope="scope">
            <span v-if="scope.row.type === 'product'">{{ scope.row.qty }}</span>
          </template>
        </el-table-column>


        <!-- <el-table-column prop="settleFlag" label="是否结算" width="100">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.settleFlag === '1'">已结算</el-tag>
           <el-tag type="danger" v-else>未结算</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column prop="totalAmount" label="总采购价" width="120"></el-table-column>
        <el-table-column prop="remark" label="备注" width="200"></el-table-column>
        <el-table-column prop="attachUrl" label="附件" width="100">
          <template slot-scope="scope">
            <a v-if="scope.row.attachUrl && scope.row.attachUrl.length" href="javascript:;"
              @click="viewAttachment(scope.row.attachUrl)">下载附件</a>
            <!-- {{  }} -->
          </template>
        </el-table-column>
        <el-table-column prop="settleFlag" label="是否结算" width="120" v-if="action === 'detail'">
          <template slot-scope="scope">
            <el-tag type="success" effect="dark"
              v-if="scope.row.type === 'supplier' && scope.row.settleFlag == '1'">已结算</el-tag>
            <el-tag type="danger" effect="dark"
              v-if="scope.row.type === 'supplier' && scope.row.settleFlag == '0'">未结算</el-tag>
          </template>
        </el-table-column>
        <!--   <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag type="success" effect="dark" v-if="scope.row.status == 1">正常</el-tag>
            <el-tag type="warning" effect="dark" v-if="scope.row.status == 0">停用</el-tag>
          </template>
        </el-table-column> -->


        <el-table-column label="创建时间" align="center" prop="createTime" width="200"></el-table-column>

        <el-table-column fixed="right" label="操作" align="center" width="200" class-name="small-padding fixed-width"
          v-if="action !== 'detail'">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"  v-if="action !== 'check' || (action === 'check' && scope.row.type === 'product')">修改</el-button>

            <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd('product', scope.row)"
               v-if="scope.row.type === 'supplier'">新增产品</el-button>

            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"   v-if="action !== 'check' || (action === 'check' && scope.row.type === 'product')">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </a-form-model>
    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 供应商表单 -->
        <template v-if="form.type === 'supplier'">
          <el-row>
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierName">
                <!-- <el-input v-model="form.supplierName" placeholder="请输入供应商名称" /> -->
                <el-select v-model="form.supplierName" placeholder="请选择" @change="handleSupplierSelect">
                  <el-option v-for="item in supOption" :key="item.value" :label="item.label" :value="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同号" prop="contractNo">
                <el-input v-model="form.contractNo" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="12" v-if="action === 'detail'">
              <el-form-item label="是否结算" prop="settleFlag">
                <el-select v-model="form.settleFlag" placeholder="请选择状态">
                  <el-option value="0" label="未结算"></el-option>
                  <el-option value="1" label="已结算"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="action === 'detail'">
              <el-form-item label="总采购价" prop="totalAmount">
                <el-input v-model="form.totalAmount" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>

          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入" type="textarea" rows="2"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="上传附件" prop="attachUrl">
                <j-upload v-model="form.attachUrl" :disabled="disabled"></j-upload>
              </el-form-item>
            </el-col>

          </el-row>
        </template>

        <!-- 产品表单 -->
        <template v-if="form.type === 'product'">
          <el-row>
            <el-col :span="24">
              <el-form-item label="所属供应商" prop="supplierName">
                <el-input v-model="form.supplierName" placeholder="所属供应商" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="产品名称" prop="productId">
                <el-select v-model="form.productId" placeholder="请选择产品名称" @change="handleProductSelect">
                  <el-option v-for="item in productOptions" :key="item.productId" :label="item.productName"
                    :value="item.productId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购单价" prop="buyUnitAmount">
                <el-input v-model="form.buyUnitAmount" placeholder="请输入单价" type="number" min="0" step="0.01" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="销售单价" prop="sealUnitAmount">
                <el-input v-model="form.sealUnitAmount" placeholder="请输入单价" type="number" min="0" step="0.01" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数量" prop="qty">
                <el-input v-model="form.qty" placeholder="请输入数量" type="number" min="1" />
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>

          </el-row>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitOrderForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAction, getFileAccessHttpUrl } from '@/api/manage'
import { ajaxGetDictItems, getDictItemsFromCache } from '@/api/api'
import { OrderFormMixin, OrderFormGridMixin } from '../../common/mixins/OrderFormMixin'
import { jvxeCustomUpload } from '@/components/jeecg/JVxeTable/components/cells/JVxeCustomUploadCell.vue'
import get from 'lodash.get';
import { MessageBox } from 'element-ui';
export default {
  name: "SupplierManagement",
  mixins: [OrderFormGridMixin, OrderFormMixin],
  components: {
    jvxeCustomUpload
  },
  /*   props: {
      // 父组件传递的初始表单数据（用于编辑场景）
      initialForm: {
        type: Object,
        default: () => ({}) // 默认空对象
      },
      // 是否禁用表单（如查看详情时）
      disabled: {
        type: Boolean,
        default: false
      },
      // 表单类型（新增/编辑）
      action: {
        type: String,
        default: 'add',
        validator: (value) => ['add', 'edit', 'detail'].includes(value) // 新增 'detail'
      }
    }, */
  watch: {
    // 监听初始数据变化，同步到子组件表单
    initialForm: {
      handler(val) {
        if (val && Object.keys(val).length) {
          this.form = { ...val }; // 深拷贝避免引用问题
        }
      },
      immediate: true // 初始化时执行
    }
  },
  data() {
    return {
      action: '',
      // disabled: false,
      model: {
        /*  attachment: "temp/2222_1759671954486.png",
         billDate: "2025-10-09",
         billNo: "2饿",
         contact: "2额饿",
         currency: "JPY",
         customerId: "1584950806756532225",
         email: "232323",
         operator: "zhagnxiao",
         phone: "2323323",
         totalAmt: 0,
         totalPayAmount: 111, */
         deliveryDate: ''
      },
      supplierList: [],
      sourceData: [

        /*   {
            "type": "supplier",
            "jsid": "supplier_1699999999999_001",
            "supplierName": "青岛高新电子贸易公司",
            "status": 1,
            "supplierId": "1584951160223113218",
            "settleFlag": "1",
            "contractNo": "23232333",
            "totalAmount": "56565",
            "remark": "青岛",
            "attachment": "temp/11111_1759669143590.png",
            "createTime": "2025-10-05 20:59:05",
            isSupplier: true,
            "productList": [
              {
                "type": "product",
                "jsid": "product_1699999999999_002",
                "supplierId": "1584951160223113218",
                "supplierName": "青岛高新电子贸易公司",
                "productName": "1970112282415984641",
                "status": 1,
                "buyUnitAmount": "2222",
                "sealUnitAmount": "44444",
                "qty": "55555",
                "createTime": "2025-10-05 20:59:39",
                "productId": "1970112282415984641",
              }
            ]
          } */

      ],
      productOptions: [

      ],
      loading: false,
      title: "",
      open: false,
      isExpandAll: false,
      hasExpandedSupplier: false,
      expandedSuppliers: new Set(),
      form: {
        id: undefined,
        type: "supplier",
        supplierName: undefined,
        supplierId: undefined,
        contractNo: "",    // 合同号
        settleFlag: "0",   // 是否结算（0=未结算，1=已结算）
        totalAmount: "",   // 总采购价
        remark: "",        // 备注
        attachUrl: [],     // 附件（假设为数组）
        status: "1",       // 状态（与原有逻辑保持一致）
        supplierList: []
      },
      rules: {
        supplierName: [{ required: true, message: "请选择供应商", trigger: "blur" }],
        contractNo: [{ required: true, message: "请输入合同号", trigger: "blur" }],
        settleFlag: [{ required: true, message: "请选择是否结算", trigger: "change" }],
        totalAmount: [
          { required: true, message: "请输入总采购价", trigger: "blur" },
          { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "金额格式错误（最多两位小数）", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择状态", trigger: "change" }
        ],
        productName: [
          { required: true, message: "请选择产品名称", trigger: "change" }
        ],
        // price: [
        //   { required: true, message: "请输入单价", trigger: "blur" },
        // ],
        quantity: [
          { required: true, message: "请输入数量", trigger: "blur" },
        ],
        settleFlag: [
          { required: true, message: "请选择结算状态", trigger: "change" }
        ],
        supplierName: [{ required: true, message: '请选择供应商', trigger: 'blur' }],
        productId: [{ required: true, message: '请选择产品', trigger: 'blur' }],
        price: [{ required: true, type: 'number', min: 0, message: '单价必须为正数', trigger: 'blur' }],
        // 为红色框圈起来的组件添加必填校验
        operator: [{ required: true, message: '请选择业务员', trigger: 'change' }],
        billNo: [{ required: true, message: '请输入单据编号', trigger: 'blur' }],
        currency: [{ required: true, message: '请选择币种', trigger: 'change' }],
        customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
        deliveryDate: [{ required: true, message: '请选择交货日期', trigger: 'change' }]
      },
      url: {
        dict: '/sys/dict/loadDictItem/',
        edit: '/wr/salOrderWr/edit',
        list: '/wr/salOrderWr/queryById'
      },
      supOption: []
    };
  },
  mounted() {
    this.expandedSuppliers.clear(); // 双重保险，确保清空
    this.hasExpandedSupplier = false;
    this.loadDataAndExpand();
    this.loadSupOptions();
    // 延迟100ms确保表格DOM已生成，再重绘一次
    setTimeout(() => {
      if (this.$refs.supplierTable) {
        this.$refs.supplierTable.doLayout();
      }
    }, 100);
  },
  methods: {
    /**
 * 转换接口返回的供应商数据为表格所需格式
 * @param {Array} rawData - 接口返回的 supplierList 原始数据
 * @returns {Array} 转换后可直接给表格使用的数据
 */
    transformSupplierData(rawData) {
      // 空数据处理
      if (!Array.isArray(rawData) || rawData.length === 0) return [];

      return rawData.map(supplier => {
        // 1. 转换供应商（父节点）数据
        const transformedSupplier = {
          ...supplier, // 保留接口返回的所有字段（id、supplierName、contractNo 等）
          type: "supplier", // 标记为供应商行
          jsid: supplier.id, // 用接口的 id 作为表格 row-key（确保唯一）
          isSupplier: true, // 标记为父节点，显示展开箭头
          isSettled: supplier.settleFlag === 1,
          // 2. 转换子产品数据（productList）
          productList: this.transformProductData(supplier.productList || [], supplier.id)
        };
        return transformedSupplier;
      });
    },

    /**
     * 转换产品子数据（给每个产品补充 type 和 jsid）
     * @param {Array} rawProducts - 原始 productList
     * @param {string} parentId - 父供应商的 id（确保产品 jsid 唯一）
     * @returns {Array} 转换后的产品数据
     */
    transformProductData(rawProducts, parentId) {
      if (!Array.isArray(rawProducts) || rawProducts.length === 0) return [];

      return rawProducts.map(product => ({
        ...product, // 保留接口返回的 productName、buyUnitAmount 等字段
        type: "product", // 标记为产品行
        jsid: product.id || `${parentId}_${Date.now()}`, // 用产品自身 id 作为 jsid（若有重复可拼接父ID：`${parentId}_${product.id}`）
        // settleFlag: false // 产品行无需结算状态，默认 false 不显示
      }));
    },
    addBefore() {
      //测试数据暂时不放开
      /*  this.sourceData = [];
       this.model={} */
    },
    editAfter() {
      if (this.model.id) {
        this.loading = true; // 显示加载中，提升用户体验
        const params = { id: this.model.id };
        this.requestSubTableData(this.url.list, params, () => {
          // 数据转换完成后，更新表格数据源并渲染
          this.loadDataAndExpand();
        });
      }

    },
    requestSubTableData(url, params, success) {
      console.log('treeTable===>');

      getAction(url, params).then(res => {
        let { result } = res
        if (result && Array.isArray(result.supplierList)) {
          // 关键：先转换接口数据为表格格式，再赋值给 sourceData
          this.sourceData = this.transformSupplierData(result.supplierList);
          console.log("转换后的数据（表格可用）：", this.sourceData); // 调试用，确认格式正确
        } else {
          this.sourceData = [];
          console.warn("接口返回的 supplierList 为空或格式错误");
          this.$message.warning("暂无供应商数据");
        }
        typeof success === 'function' ? success(res) : ''
      }).finally(() => {
        this.loading = false;
      })
    },
    /** 当点击新增按钮时调用此方法 */
    add() {
      console.log('saleorderadd===>');
      this.action = 'add';
      if (typeof this.addBefore === 'function') this.addBefore()
      // 默认新增空数据
      let rowNum = this.addDefaultRowNum
      if (typeof rowNum !== 'number') {
        rowNum = 1
        console.warn('由于你没有在 data 中定义 addDefaultRowNum 或 addDefaultRowNum 不是数字，所以默认添加一条空数据，如果不想默认添加空数据，请将定义 addDefaultRowNum 为 0')
      }
      if (rowNum > 0) {
        let newRows = new Array(rowNum).fill({})
        this.eachAllTable((item) => {
          //update-begin-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349
          setTimeout(() => {
            item.addRows(newRows)
          }, 30)
          //update-end-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349
        })
      }
      if (typeof this.addAfter === 'function') this.addAfter(this.model)
      this.edit(this.model)
    },
    /** 当点击了编辑（修改）按钮时调用此方法 */
    edit(record, action) {
      console.log('编辑按钮点击了参数是', record,action);
      this.action = action;
      this.visible = true
      this.$refs.form.resetFields()
      this.model = Object.assign({}, record)
      console.log('model===>', this.model);

      if (typeof this.editAfter === 'function') this.editAfter(this.model)
    },
    /** 关闭弹窗，并将所有JVxeTable实例回归到初始状态 */
    close() {
      this.visible = false
      this.action = ''
      this.eachAllTable((item) => {
        item._remove()
      })
      this.$emit('close')
    },
    // 生成唯一ID（格式：前缀_时间戳_随机数）
    generateUniqueId(prefix) {
      const timestamp = new Date().getTime(); // 时间戳（毫秒级，确保不重复）
      const random = Math.floor(Math.random() * 1000); // 随机数（进一步避免冲突）
      return `${prefix}_${timestamp}_${random}`;
    },
    handleProductSelect(productId) {
      // 遍历productOptions找到匹配的项
      const selectedProduct = this.productOptions.find(item => item.productId === productId);
      if (selectedProduct) {
        console.log("选中的产品名称：", selectedProduct.productName);
        // 这里就可以使用selectedProduct.productName了
        this.form.productName = selectedProduct.productName
      }
    },

    viewAttachment(urls) {
      // 可根据实际需求实现附件预览（如弹窗、新窗口等）
      if (!urls) return;
      console.log('预览开始调用');

      // 若 j-upload 返回的是数组（多数情况），取第一个；若是字符串直接用
      const url = Array.isArray(urls) ? urls[0] : urls;
      // 拼接正确的预览地址（按你项目的地址规则调整）
      //  window._CONFIG['staticDomainURL'] + "/" + url;
      window.open(`${window._CONFIG['staticDomainURL']}/${url}`, '_blank');
    },
    handleSupplierSelect(selectedName) {
      // console.log('selectedId',selectedId);
      const selectedItem = this.supOption.find(item => item.label === selectedName);
      if (selectedItem) {
        this.form.supplierId = selectedItem.value; // 同步ID到form.supplierId
      } else {
        this.form.supplierId = undefined;
      }
    },
    loadSupOptions() {
      ajaxGetDictItems('bas_supplier,name,id').then(res => {
        console.log('res', res);
        this.supOption = res.result;
      });
    },
    loadDataAndExpand() {
      this.loading = true;
      this.supplierList = JSON.parse(JSON.stringify(this.sourceData)).map(item => {
        if (item.type === 'supplier') {
          return {
            ...item, isSupplier: true, productList: item.productList || [] // 强制转为数组，避免undefined
          }; // 供应商标记为有子节点
        }
        return item; // 产品行不添加，默认无
      });
      /*  if (item.type === 'product') {
         delete item.productList;
       } */
      this.supplierList.settleFlag = Number(this.supplierList.settleFlag)
      this.$nextTick(() => {
        this.loading = false;
        // 可选：页面加载后触发一次表格重绘，确保配置生效
        if (this.$refs.supplierTable) {
          this.$refs.supplierTable.doLayout();
        }
      });
    },
    // 处理展开折叠变化
    handleExpandChange(row, expanded) {
      if (row.type === 'supplier') {
        if (expanded) {
          this.expandedSuppliers.add(row.supplierId);
        } else {
          this.expandedSuppliers.delete(row.supplierId);
        }
        // 严格根据集合大小更新，避免其他逻辑干扰
        this.hasExpandedSupplier = this.expandedSuppliers.size > 0;
        console.log('当前展开的供应商数量：', this.expandedSuppliers.size); // 调试用，确认是否正确触发
      }
    },
    queryProduct(supid) {
      console.log('supid', supid);
      getAction('/base/basSupplier/queryById', { id: supid }).then(res => {
        console.log('res', res);
        this.productOptions = res.result.productList;
      });
    },

    toggleExpandAll() {
      this.isExpandAll = !this.isExpandAll;
      this.expandedSuppliers.clear();

      if (this.isExpandAll && this.supplierList.length) {
        this.supplierList.forEach(supplier => {
          this.$refs.supplierTable.toggleRowExpansion(supplier, true);
          this.expandedSuppliers.add(supplier.supplierId);
        });
        this.hasExpandedSupplier = true;
      } else {
        this.supplierList.forEach(supplier => {
          this.$refs.supplierTable.toggleRowExpansion(supplier, false);
        });
        this.hasExpandedSupplier = false;
      }
    },
    handleAdd(type, parent) {
      if (type === 'supplier') {
        this.form = {
          supplierId: undefined,
          type: "supplier",
          supplierName: "",
          status: "1"
        };
        this.title = "新增供应商";

      } else {
        this.form = {
          type: "product",
          supplierId: parent.supplierId,
          supplierName: parent.supplierName,
          productName: this.form.productName,
          buyUnitAmount: this.form.buyUnitAmount,
          sealUnitAmount: this.form.sealUnitAmount,
          qty: this.form.qty,
          status: this.form.status,
          settleFlag: this.form.settleFlag,
        };
        this.title = `在【${parent.supplierName}】下新增产品`;
        console.log('parent', parent);

        this.queryProduct(parent.supplierId);
      }

      this.open = true;
    },
    handleUpdate(row) {
      this.form = JSON.parse(JSON.stringify(row));
      /*     this.form.status = this.form.status.toString();
          this.form.settleFlag = this.form.settleFlag.toString(); */
      if (row.type === 'supplier') {
        this.form.settleFlag = row.settleFlag.toString();
      }
      this.title = row.type === 'supplier' ? "修改供应商" : "修改产品";
      this.open = true;
    },
    submitOrderForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const formData = {
            ...this.form,
            status: Number(this.form.status),
            settleFlag: Number(this.form.settleFlag),
            createTime: this.form.id ? this.form.createTime : this.parseTime(new Date())
          };

          if (this.form.id) {
            console.log('进入修改逻辑');

            this.updateNode(this.sourceData, formData);
            this.$message.success(formData.type === 'supplier' ? "供应商修改成功" : "产品修改成功");
          } else {
            // 新增供应商逻辑
            if (formData.type === 'supplier') {
              formData.jsid = this.generateUniqueId('supplier'); // 关键：动态生成ID
              formData.productList = [];
              formData.isSupplier = true;
              formData.supplierName = this.form.supplierName; // 保存供应商名称（表格显示用）
              // formData.supplierId = this.form.supplierId; // 提交时使用供应商ID
              formData.contractNo = this.form.contractNo;   // 保存合同号
              formData.settleFlag = this.form.settleFlag;   // 保存结算状态
              formData.totalAmount = this.form.totalAmount; // 保存总采购价
              formData.remark = this.form.remark;           // 保存备注
              formData.attachUrl = this.form.attachUrl;     // 保存附件
              this.sourceData.push(formData);
            } else {
              console.log('进入新增产品逻辑公用变量foramdata', formData);
              const supplier = this.sourceData.find(s => s.supplierId === formData.supplierId);
              if (supplier) {
                formData.jsid = this.generateUniqueId(`product_${supplier.jsid}`); // 包含父ID，便于关联
                formData.productName = this.form.productName;
                formData.productId = this.form.productId;
                formData.qty = this.form.qty;
                formData.buyUnitAmount = this.form.buyUnitAmount;
                formData.sealUnitAmount = this.form.sealUnitAmount;
                if (!supplier.productList) supplier.productList = [];
                supplier.productList.push(formData);
              }
            }
            this.$message.success(formData.type === 'supplier' ? "供应商新增成功" : "产品新增成功");
          }
          // let orderData = this.classifyIntoFormData(this.sourceData)
          // this.$emit('ok', orderData);

          console.log('新增后的产品表格数据是：', this.sourceData);

          this.open = false;
          this.loadDataAndExpand();
        }
      });
    },
    submitForm() {
      console.log('提交表单');
      
      // 先进行表单校验
      this.$refs.form.validate(valid => {
        if (valid) {
          // 校验成功后执行原有逻辑
          let orderData = this.classifyIntoFormData(this.sourceData)
          if(this.action==='check'){
             this.$emit('check', orderData);
             return
          }
          if (this.model.id) {
            this.$emit('edit', orderData);
          } else {
            this.$emit('add', orderData)
          }
        } else {
          // 校验失败
          console.log('表单校验失败');
          return false;
        }
      });

    },
    handleCancel() {
      this.$emit('cancel'); // 取消操作：通知父组件
    },
    updateNode(nodes, data) {
      for (let i = 0; i < nodes.length; i++) {
        // 关键：用jsid判断唯一行
        if (nodes[i].jsid === data.jsid) {
          // 供应商行强制保留isSupplier: true
          if (data.type === 'supplier') {
            data.isSupplier = true;
          }
          nodes[i] = { ...nodes[i], ...data };
          return true;
        }
        if (nodes[i].productList && nodes[i].productList.length) {
          if (this.updateNode(nodes[i].productList, data)) {
            return true;
          }
        }
      }
      return false;
    },
    handleDelete(row) {
      const confirmText = row.type === 'supplier'
        ? `确定删除供应商"${row.supplierName}"及其所有产品吗？`
        : `确定删除产品"${row.productName}"吗？`;
      console.log('删除行this', this);

      MessageBox.confirm(confirmText, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.deleteNode(this.sourceData, row.jsid);
        if (row.type === 'supplier') {
          this.expandedSuppliers.delete(row.jsid);
          this.hasExpandedSupplier = this.expandedSuppliers.size > 0;
        }
        this.loadDataAndExpand();
        this.$message.success(row.type === 'supplier' ? "供应商删除成功" : "产品删除成功");
      });
    },
    deleteNode(nodes, jsid) { // 参数名也改为jsid，更清晰
      for (let i = 0; i < nodes.length; i++) {
        // 关键：用jsid判断唯一行
        if (nodes[i].jsid === jsid) {
          nodes.splice(i, 1);
          return true;
        }
        if (nodes[i].productList && nodes[i].productList.length) {
          if (this.deleteNode(nodes[i].productList, jsid)) {
            return true;
          }
        }
      }
      return false;
    },
    parseTime(time) {
      if (!time) return "";
      const date = new Date(time);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
    },
    cancel() {
      this.open = false;
    },
    classifyIntoFormData(sourceData) {

      // 深拷贝避免修改原数据，同时清理冗余字段（isSettled、isSupplier 等）
      const cleanSupplierList = JSON.parse(JSON.stringify(sourceData)).map(item => {
        if (item.type === 'supplier') {
          // 删除仅前端用的字段，避免后端接收多余数据
          delete item.isSettled;
          delete item.isSupplier;
          // 兜底：确保 settleFlag 是 Integer（防止意外转为其他类型）
          item.settleFlag = Number(item.settleFlag);
          // 清理产品列表的冗余字段
          item.productList = item.productList.map(prod => {
            delete prod.type; // 产品类型仅前端用
            return prod;
          });
        }
        return item;
      });

      return {
        ...this.model,
        supplierList: cleanSupplierList,
      }

    },
    resetForm() {
      this.$refs.form.resetFields();
      this.form = { ...this.initialForm }; // 重置为初始数据
    },
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.fixed-width {
  width: 220px;
}

/* 核心：将箭头移到供应商名称后面 */
::v-deep .el-table__expand-icon {
  /* 移除默认左浮动 */
  float: none;
  /* 让箭头在文字后面显示 */
  display: inline-block;
  margin-left: 8px;
  /* 名称和箭头之间的间距 */
  margin-right: 0;
  vertical-align: middle;
}

/* 调整树形单元格内容的布局 */
::v-deep .el-table__cell>.cell {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

/* 优化子节点缩进 */
::v-deep .el-table__indent {
  padding-right: 8px;
}

/* 箭头动画效果保持 */
::v-deep .el-table__expand-icon--expanded {
  transform: rotate(90deg);
}

/* 列显示/隐藏过渡 */
::v-deep .el-table__header colgroup col,
::v-deep .el-table__body colgroup col {
  transition: width 0.3s ease;
}

::v-deep .el-dialog__header {
  text-align: center;
  padding: 10px;
  background-color: #1890FF;
}

::v-deep .el-dialog__title {
  line-height: 24px;
  font-size: 18px;
  color: #fff;
}
</style>
